package com.ajavaer.framework;

import com.ajavaer.framework.cache.type.CacheEngine;
import com.ajavaer.framework.config.CacheConfig;
import com.ajavaer.framework.config.CacheEngineConfig;
import com.ajavaer.framework.handle.CacheHandle;
import com.ajavaer.framework.handle.CaffeineHandle;
import com.ajavaer.framework.handle.RedisHandle;
import com.ajavaer.framework.handle.impl.CaffeineHandleImpl;
import com.ajavaer.framework.handle.impl.RedisHandleImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AjavaerCache {

    public static final AjavaerCache ME = new AjavaerCache();

    private CacheConfig cacheConfig;

    private Map<CacheEngine, CacheHandle> handles = new HashMap<>();

    public void init(CacheConfig cacheConfig, ApplicationContext context) {
        this.cacheConfig = cacheConfig;
        List<CacheEngineConfig> engines = cacheConfig.getEngines();
        Iterator<CacheEngineConfig> handleIter = engines.iterator();
        while (handleIter.hasNext()) {
            CacheEngineConfig engineConfig = handleIter.next();
            CacheEngine engine = engineConfig.getEngine();
            switch (engine) {
                case caffeine:
                    CaffeineHandleImpl caffeineCacheHandle = new CaffeineHandleImpl();
                    caffeineCacheHandle.init(engineConfig,context);
                    handles.put(engine, caffeineCacheHandle);
                    break;
                case redis:
                    RedisHandle redisCacheHandle = new RedisHandleImpl();
                    redisCacheHandle.init(engineConfig,context);
                    handles.put(engine, redisCacheHandle);
                    break;

            }
        }

    }

    /**
     * 获取redis句柄
     *
     * @return
     */
    public static RedisHandle redis() {
        return (RedisHandle) get(CacheEngine.redis);
    }

    /**
     * 获得caffeine句柄
     *
     * @return
     */
    public static CaffeineHandle caffeine() {
        return (CaffeineHandle) get(CacheEngine.caffeine);
    }

    public static CacheHandle get(CacheEngine cacheEngine) {
        return ME.handles.get(cacheEngine);
    }

    public static boolean has(CacheEngine cacheEngine) {
        return ME.handles.get(cacheEngine) != null;
    }


}
